package handler;

import codec.PacketCodeC;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import packet.AbstractPacket;
import packet.impl.LoginRequestAbstractPacket;
import packet.impl.LoginResponseAbstractPacket;
import packet.impl.MessageResponseAbstractPacket;
import utils.LoginUtil;

import java.util.Date;
import java.util.UUID;

/**
 * @author Admin
 */
public class ClientHandler extends ChannelInboundHandlerAdapter {
  @Override
  public void channelActive(ChannelHandlerContext ctx) {
    System.out.println(new Date() + "客户端开始登陆");

    // 创建对象
    LoginRequestAbstractPacket packet = new LoginRequestAbstractPacket();
    packet.setVersion((byte) 1);
    packet.setUserId(UUID.randomUUID().toString());
    packet.setUserName("Captainhzy");
    packet.setPassword("693909");

    // 编码
    ByteBuf buf = PacketCodeC.INSTANCE.encode(ctx.alloc(), packet);

    // 写数据
    ctx.channel().writeAndFlush(buf);
  }

  @Override
  public void channelRead(ChannelHandlerContext ctx, Object msg) {
    ByteBuf responseByteBuf = (ByteBuf) msg;
    AbstractPacket responsePacket = PacketCodeC.INSTANCE.decode(responseByteBuf);

    if (responsePacket instanceof LoginResponseAbstractPacket) {
      LoginResponseAbstractPacket loginResponsePacket = (LoginResponseAbstractPacket) responsePacket;
      if (loginResponsePacket.getSuccess()) {
        LoginUtil.markAsLogin(ctx.channel());
        System.out.println(new Date() + "登陆成功");
      } else {
        System.out.println(new Date() + "登陆失败，原因：" + loginResponsePacket.getReason());
      }
    } else if (responsePacket instanceof MessageResponseAbstractPacket) {
      MessageResponseAbstractPacket messageResponsePacket = (MessageResponseAbstractPacket) responsePacket;
      System.out.println(new Date() + ": 收到服务端的消息：" + messageResponsePacket.getMessage());
    }
  }
}
